use codegraph_lsp::{LspServerManager, LspManagerConfig};
use std::path::PathBuf;
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::fmt::init();

    println!("🚀 LSP Server Manager Usage Example");

    // 1. 创建配置
    let config = if let Ok(config_path) = std::env::var("LSP_CONFIG_PATH") {
        println!("📄 Loading config from: {}", config_path);
        LspManagerConfig::load_from_file(&PathBuf::from(config_path))?
    } else {
        println!("📄 Using default configuration");
        LspManagerConfig::default()
    };

    // 2. 创建管理器
    let manager = LspServerManager::new(config);

    // 3. 启动管理器
    println!("🔧 Starting LSP manager...");
    manager.start().await;

    // 4. 发现文件对应的服务器
    let test_files = vec![
        "example.py",
        "example.rs", 
        "example.ts",
        "example.java",
        "example.cpp",
        "example.go",
        "unknown.xyz"
    ];

    println!("\n🔍 Discovering servers for test files:");
    for file in &test_files {
        if let Some(language) = manager.discover_server_for_file(file).await {
            println!("  {} -> {}", file, language);
        } else {
            println!("  {} -> No server found", file);
        }
    }

    // 5. 尝试启动一些服务器
    println!("\n🚀 Attempting to start servers:");
    let languages = vec!["python", "rust", "typescript"];
    
    for language in &languages {
        println!("  Starting {} server...", language);
        match manager.start_server(language).await {
            Ok(server_id) => {
                println!("    ✅ Started successfully: {}", server_id);
            }
            Err(e) => {
                println!("    ❌ Failed to start: {}", e);
            }
        }
    }

    // 6. 检查服务器状态
    println!("\n📊 Server status:");
    let all_status = manager.get_all_server_status().await;
    for (language, status) in &all_status {
        println!("  {}: {:?}", language, status);
    }

    // 7. 获取资源统计
    println!("\n📈 Resource statistics:");
    for language in &languages {
        if let Some(stats) = manager.get_server_stats(language).await {
            println!("  {} stats:", language);
            println!("    CPU: {:.2}%", stats.cpu_usage);
            println!("    Memory: {} bytes", stats.memory_usage);
            println!("    Requests: {}", stats.requests_handled);
            println!("    Avg response time: {:.2}ms", stats.avg_response_time);
            println!("    Errors: {}", stats.error_count);
        }
    }

    // 8. 测试重启功能
    println!("\n🔄 Testing restart functionality:");
    for language in &languages {
        if all_status.get(*language).is_some() {
            println!("  Restarting {} server...", language);
            match manager.restart_server(language).await {
                Ok(server_id) => {
                    println!("    ✅ Restarted successfully: {}", server_id);
                }
                Err(e) => {
                    println!("    ❌ Failed to restart: {}", e);
                }
            }
        }
    }

    // 9. 等待一段时间让健康检查运行
    println!("\n⏳ Waiting for health checks to run...");
    sleep(Duration::from_secs(5)).await;

    // 10. 再次检查状态
    println!("\n📊 Final server status:");
    let final_status = manager.get_all_server_status().await;
    for (language, status) in &final_status {
        println!("  {}: {:?}", language, status);
    }

    // 11. 演示配置更新
    println!("\n⚙️  Testing configuration update:");
    let mut new_config = manager.get_config().await;
    new_config.global_settings.enable_diagnostics = false;
    new_config.global_settings.max_completion_items = 50;
    
    manager.update_config(new_config).await;
    println!("  Configuration updated successfully");

    let updated_config = manager.get_config().await;
    println!("  Diagnostics enabled: {}", updated_config.global_settings.enable_diagnostics);
    println!("  Max completion items: {}", updated_config.global_settings.max_completion_items);

    // 12. 停止特定服务器
    println!("\n🛑 Stopping individual servers:");
    for language in &languages {
        if final_status.get(*language).is_some() {
            println!("  Stopping {} server...", language);
            match manager.stop_server(language).await {
                Ok(()) => {
                    println!("    ✅ Stopped successfully");
                }
                Err(e) => {
                    println!("    ❌ Failed to stop: {}", e);
                }
            }
        }
    }

    // 13. 停止管理器
    println!("\n🛑 Stopping LSP manager...");
    let _ = manager.stop().await;
    println!("✅ LSP manager stopped successfully");

    println!("\n🎉 Example completed!");
    Ok(())
}

// 辅助函数：打印分隔线
#[allow(dead_code)]
fn print_separator(title: &str) {
    println!("\n{}", "=".repeat(50));
    println!("  {}", title);
    println!("{}", "=".repeat(50));
}
